from zope.interface import implements

from axiom import item, store, attributes, sequence
from epsilon.extime import Time

from nevow import tags as t

import const
from iwiki import IWiki, IWikiWord

class WikiWord(item.Item):

    implements(IWikiWord)

    typeName = "WikiWord"
    schemaVersion = 1

    word = attributes.text(indexed=True, allowNone=False)
    ispage = attributes.boolean(indexed=True, default=False)

    def __init__(self, **kw):
        print "Creating WikiWord '%s'..." % kw.get('word')
        super(WikiWord, self).__init__(**kw)

    def installOn(self, other):
        super(WikiWord, self).installOn(other)
        other.powerUp(self, IWiki)

    def isPage(self, word):
        if self.ispage:
            return True
        return False

    def setHasPage(self, word):
        self.ispage = True

class WikiPost(item.Item):
    typeName = "WikiPost"
    schemaVersion = 1

    id = attributes.text(indexed=True, allowNone=False)
    created = attributes.timestamp(indexed=True)
    modified = attributes.timestamp(indexed=True)
    title = attributes.text(indexed=True, allowNone=False)
    author = attributes.text(indexed=True, allowNone=False)
    category = attributes.text(indexed=True)
    content = attributes.text(indexed=True)
    wikiPages = attributes.reference()

    def __init__(self, **kw):
        now = Time()
        print kw
        kw.update({'created':now,
                   'modified':now})
        super(WikiPost, self).__init__(**kw)
        self.wikiPages = sequence.List(store=self.store)
        self.recordWikiWords()

    def recordWikiWords(self):
        '''
        wiki word processing
        '''
        for word in self.content.split(' '):
            if const.matchWikiWord(word):
                # add to index
                if word not in [x.word for x in self.wikiPages ]:
                    wikiPage = WikiWord(store=self.store, word=word)
                    self.wikiPages.append(wikiPage)

    def setModified(self):
        self.modified = Time()

    def getPostsWikiPages(self):
        return [x.word for x in self.store.wikiPages]

class Wiki(item.Item, item.InstallableMixin):

    implements(IWiki)

    typeName = "Wiki"
    schemaVersion = 1

    posts = attributes.reference()
    
    def __init__(self, **kw):
        super(Wiki, self).__init__(**kw)
        self.posts = sequence.List(store=self.store)
        for pageClass in const.getPreinstalledPages():
            page = pageClass()
            post = WikiPost(store=self.store,
                id=page.id,
                author=page.author,
                title=page.title,
                category=page.category,
                content=page.content)
            self.updatePost(post)
            self.posts.append(post)

    def installOn(self, other):
        super(Wiki, self).installOn(other)
        other.powerUp(self, IWiki)

    def updatePost(self, post):
        #self.posts.append(post)
        self.processWikiWords(post)
        post.recordWikiWords()

    def processWikiWords(self, post):
        ww = self.store.findOrCreate(WikiWord, word=post.id)
        ww.ispage = True

    def getPosts(self, howMany=10):
        """
        """
        return list(self.store.query(WikiPost))[:howMany]

    def getCategories(self):
        """
        """
        return [{'url':'/byCategory/%s' % x, 'text':x} for x in const.categories ]

    def getPage(self, id):
        id = unicode(id)
        print "Looking for page %s" % id
        return self.store.findFirst(WikiPost, WikiPost.id == id)

    getPost = getPage

    def getPostsByCategory(self, category):
        category = unicode(category)
        return self.store.query(WikiPost, WikiPost.category == category)

    def getExistingWikiPages(self):
        query = self.store.query(WikiWord, WikiWord.ispage == True)
        results = [x.word for x in query]
        results.sort()
        return [{'text':word,'url':'/%s' % word} for word in results]

    def getPendingWikiPages(self):
        query = self.store.query(WikiWord, WikiWord.ispage == False)
        results = [x.word for x in query]
        results.sort()
        return [{'text':word,'url':'/%s' % word} for word in results]

    def isMakePage(self, check):
        print "Checking page '%s'..." % check
        check = unicode(check)
        result = self.store.findFirst(WikiWord, WikiWord.word == check)
        if result and not result.ispage:
            return True
        return False

def initialize(storename):
    s = store.Store(storename)
    s.findOrCreate(Wiki).installOn(s)
    #s.findOrCreate(WikiWord).installOn(s)
    return s
